package com.itheima.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/JSONTestServlet")
public class JSONTestServlet extends HttpServlet {
//获取传输过来的JSON对象

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("post方法");
        //获得请求输入流
        BufferedReader reader = req.getReader();
        //这里用的读一行  所以发送过来的信息要写一行里面
        String json = reader.readLine();
        System.out.println("JSON字符串" + json);
        //将字符串转化为JSON对象
        User user = JSON.parseObject(json, User.class);
        System.out.println("转化后的java对象:" + user);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User(1,"老王","123456",500.0);
        String jsonString = JSON.toJSONString(user);
        PrintWriter out = resp.getWriter();
        out.println(jsonString);
    }
}
